from hep.aida import *

from java.awt import Color
from java.awt import Font
from java.lang import *
from java.util import *
from java.io import *
from java.text import DecimalFormat


from jhplot.jadraw import *
from jhplot  import *

from fr.in2p3.ipnl.aidautilities import *

from jscinttools.datafit import *
from jscinttools.datafit.scint import *
from jscinttools.utilities.aidautilities import *
from jscinttools.utilities.jhplotutilities import *
from jscinttools.utilities.scintutilities import *

Locale.setDefault(Locale.ENGLISH)
System.getProperties().setProperty("hep.aida.BatchAnalysisFactory","hep.aida.ref.BatchAnalysisFactory")
ff = FitFuncFactory.pulseFuncFactory()

showFigures = False
writeFigures = not showFigures

""" Define colors and fonts"""
figType = [".png", ".eps", ".pdf"]
colors = [Color.blue, Color.red, Color(0, 170, 0), Color.black, Color.yellow]
axisLabelFont = Font(Font.SERIF, Font.PLAIN, 25)
titleFont = Font(Font.SERIF, Font.PLAIN, 25)
legendFont = Font(Font.SERIF, Font.PLAIN, 25)
ticFont = Font(Font.SERIF, Font.PLAIN, 20)
statBoxFont = Font(Font.SERIF, Font.PLAIN, 15)

""" Define the Path and files names"""
#aidaPath = "/home/marc-antoine/Documents/ZnWO4/Run_5/Reduced/TDC/2011_07_04/"
#aidaFile = "Am241Cs137_295K_511_PhotonReanalysis_NoTuples"
#outPath = aidaPath
#startPar = [0.5, 0.5, 0.1, 3.7, 0.36, 14.3, 0.000007]
##startPar = [0.5, 1.5, 0.36, 14.3, 0.000007]
#fitFunc = ff.nExpBck()
#win = [0, 150, 0.00001, 1]
#winZoom = [0, 10, 0.1, 1]
#title = "Average Pulse in ZnWO_{4} with ^{137}Cs at 295 K"
#preliminary = True

aidaPath = "/home/marc-antoine/Documents/ZnWO4/Run_5/Reduced/TDC/2011_07_04/"
aidaFile = "Am241_295K_511_PhotonReanalysis_NoTuples"
outPath = aidaPath
startPar = [0.5, 0.5, 0.1, 3.7, 0.36, 14.3, 0.000007]
#startPar = [0.5, 1.5, 0.36, 14.3, 0.000007]
fitFunc = ff.nExpBck()
win = [0, 150, 0.00001, 1]
winZoom = [0, 10, 0.1, 1]
title = "Average Pulse in ZnWO_{4} with ^{241}Am at 295 K"
preliminary = True

#aidaPath = "/home/marc-antoine/Documents/jCode/Dropbox/CryoDAQ/Reduced_Data/2011_03_16/"
#aidaFile = "Na22_3200mK_001_PhotonReanalysis_NoTuples"
#outPath = aidaPath
#startPar = [1, 0.7, 0.2, 32, 0.1, 215.0, 0.00001]
##startPar = [0.2, 0.8, 0.1, 30.0, 0.00001]
#fitFunc = AvEventBckFit(startPar)
#win = [0, 1800, 0.00001, 1]
#winZoom = [0, 10, 0.1, 1]
#title = "Average Pulse in ZnWO_{4} with ^{22}Na at 3.2 K"
#preliminary = True


#aidaPath = "/home/marc-antoine/Documents/jCode/Dropbox/CryoDAQ/Reduced_Data/2011_03_30/"
#aidaFile = "Na22_10K_001_PhotonReanalysis_NoTuples"
#outPath = aidaPath
#startPar = [0.3, 0.7, 0.2, 11, 0.6, 52.0, 0.00001]
##startPar = [0.2, 0.5, 0.1, 30.0, 0.00001]
#fitFunc = AvEventBckFit(startPar)
#win = [0, 800, 0.000001, 1]
#winZoom = [0, 10, 0.1, 1]
#title = "Average Pulse in ZnWO_{4} with ^{22}Na at 10 K"
#preliminary = True


#aidaPath = "/home/marc-antoine/Documents/jCode/Dropbox/CryoDAQ/Reduced_Data/2011_03_31/"
#aidaFile = "Na22_20K_001_PhotonReanalysis_NoTuples"
#outPath = aidaPath
#startPar = [0.3, 0.7, 0.2, 6, 0.6, 30.0, 0.00001]
##startPar = [0.2, 6, 0.6, 30.0, 0.00001]
#fitFunc = AvEventBckFit(startPar)
#win = [0, 500, 0.000001, 1]
#winZoom = [0, 10, 0.1, 1]
#title = "Average Pulse in ZnWO_{4} with ^{22}Na at 20 K"
#preliminary = True

#aidaPath = "/home/marc-antoine/Documents/jCode/Dropbox/CryoDAQ/Reduced_Data/2011_03_31/"
#aidaFile = "Na22_7K_001_PhotonReanalysis_NoTuples"
#outPath = aidaPath
#startPar = [0.8, 0.4, 0.11, 15.0, 0.3, 82.0, 0.00002]
#fitFunc = AvEventBckFit(startPar)
#win = [0, 1500, 0.000001, 1]
#winZoom = [0, 10, 0.1, 1]
#title = "Average Pulse in ZnWO_{4} with ^{22}Na at 7 K"
#preliminary = True

#aidaPath = "/home/marc-antoine/Documents/ZnWO4/Reduced_Data/Na22_294K_001"
#aidaFile = "Na22_294K_001_PhotonReanalysis_NoTuples"
#outPath = "/home/marc-antoine/Dropbox/ZnWO4"
#aidaPath = "/home/marc-antoine/Documents/jCode/Dropbox/CryoDAQ/Reduced_Data/2011_03_28/"
#aidaFile = "Na22_294K_002_PhotonReanalysis_NoTuples"
#outPath = aidaPath
#startPar = [0.5, 1, 0.6, 13, 0.001]
#fitFunc = AvEventBckFit(startPar)
#win = [0, 180, 0.00001, 1]
#winZoom = [0, 10, 0.1, 1]
#title = "Average Pulse in ZnWO_{4} with ^{22}Na at 294 K"
#preliminary = True

outputFile = aidaFile.split("_PhotonReanalysis_NoTuples")[0]
avEvtPath = "Reanalysis/Average pulse shapes/Variable binning/Weighted Average Pulse from First Photon on Ch2, Ch1, All Cuts"
#avEvtPath = "Reanalysis/Average pulse shapes/Variable binning/Special Bin, Average Pulse from First Photon on Ch1, Ch0, All Cuts"

afr = AidaFileReader(aidaPath, aidaFile)
avEvtHisto = afr.grabHisto1D(avEvtPath)
avEvtHisto.scale(1.0 / avEvtHisto.maxBinHeight())


#sdf = ScintDataFit(fitFunc)
#sdf.doFit(avEvtHisto)

df = DataFitter(fitFunc)
fs = FitSettings(startPar)



"""
###############################################################
# Plotting Part
###############################################################
"""
""" Create the plottable JHep objects from AIDA IObjects"""

	
avEvt = H1D(avEvtHisto, title=aidaFile, style="h", color=colors[0], penWidth=2, errAll=False)

#fitRes = sdf.fitResult
fitRes = df.doFit(avEvtHisto, fs)
print(AidaUtil.printResultsOfFit(fitRes))
amp = []
tau = []
ampErr = []
tauErr = []
for i in range(len(fitRes.fittedParameters())/2):
	amp.append(fitRes.fittedParameters()[i * 2])
	tau.append(fitRes.fittedParameters()[(i * 2) + 1])
	ampErr.append(fitRes.errors()[i * 2])
	tauErr.append(fitRes.errors()[(i * 2) + 1])
	
frac = []
fracErr = []
for i in range(len(fitRes.fittedParameters())/2):	
	frac.append(ScintUtil.calcLYFrac(i, amp, tau))
	fracErr.append(ScintUtil.calcLYFracErr(i, amp, ampErr, tau, tauErr))

fit = F1D(fitRes.fittedFunction(), win[0], win[1], points=1000, title="Fit", color=colors[1], penWidth=2)
fitZoom = F1D(fitRes.fittedFunction(), winZoom[0], winZoom[1], points=1000, title="Fit", color=colors[1], penWidth=2)
fitZoom.setMin(winZoom[0])
fitZoom.setMax(winZoom[1])

fmt = DecimalFormat("#.###");
fmtSc = DecimalFormat("0.###E0");

statLine = []
#statLine.append("A_{0} = " + String.valueOf(fmt.format(fitRes.fittedParameters()[0])) + ' &plusmn; ' + String.valueOf(fmt.format(fitRes.errors()[0])))
statLine.append("Fn_{0} = " + String.valueOf(fmt.format(frac[0])) + ' &plusmn; ' + String.valueOf(fmt.format(fracErr[0])))
statLine.append("&tau;_{0} = " + String.valueOf(fmt.format(fitRes.fittedParameters()[1])) + ' &plusmn; ' + String.valueOf(fmt.format(fitRes.errors()[1])) + ' &micro;s ')
#statLine.append("A_{1} = " + String.valueOf(fmt.format(fitRes.fittedParameters()[2])) + ' &plusmn; ' + String.valueOf(fmt.format(fitRes.errors()[2])))
statLine.append("Fn_{1} = " + String.valueOf(fmt.format(frac[1])) + ' &plusmn; ' + String.valueOf(fmt.format(fracErr[1])))
statLine.append("&tau;_{1} = " + String.valueOf(fmt.format(fitRes.fittedParameters()[3])) + ' &plusmn; ' + String.valueOf(fmt.format(fitRes.errors()[3])) + ' &micro;s ')
#statLine.append("A_{2} = " + String.valueOf(fmt.format(fitRes.fittedParameters()[4])) + ' &plusmn; ' + String.valueOf(fmt.format(fitRes.errors()[4])))
statLine.append("Fn_{2} = " + String.valueOf(fmt.format(frac[2])) + ' &plusmn; ' + String.valueOf(fmt.format(fracErr[2])))
statLine.append("&tau;_{2} = " + String.valueOf(fmt.format(fitRes.fittedParameters()[5])) + ' &plusmn; ' + String.valueOf(fmt.format(fitRes.errors()[5])) + ' &micro;s ')
statLine.append("Ct = " + String.valueOf(fmtSc.format(fitRes.fittedParameters()[6])) + ' &plusmn; ' + String.valueOf(fmtSc.format(fitRes.errors()[6])))
statLine.append('&Chi;^{2} = ' + String.valueOf(fmt.format(fitRes.quality())))

statBox = []
for i in range (len(statLine)):
	statBox.append(JaText(statLine[i], 0.17, 0.60+(i*0.035), "NDC", font=statBoxFont, color=colors[3]))
	
prelim = JaText("Preliminary", 0.175, 0.2, "NDC", font=titleFont, color=colors[1])
""" Create the Plotter"""
mainPlotter = HPlotJa("Average Event", 600, 600, 2, 1, True)
mainPlotter.setGTitle(title, titleFont)
mainPlotter.antiAlias = False
if showFigures:
	mainPlotter.visible(True)
else:
	mainPlotter.visible(False)
	
mainPlotter.cd(1,1)	
mainPlotter.setPad(1, 1, 0.125, 0.125, 0.75, 0.75)
mainPlotter.setRange(win[0], win[1], win[2], win[3])
mainPlotter.setLogScale(0, False)
mainPlotter.setLogScale(1, True)
mainPlotter.ticFont = ticFont
mainPlotter.showStatBox = False
mainPlotter.showKey(False)
mainPlotter.nameX = "Time (&micro;s)"
mainPlotter.nameY = "Photons / Time Unit"

mainPlotter.cd(2,1)	
mainPlotter.setPad(2, 1, 0.525, 0.17, 0.3, 0.3)
mainPlotter.setRange(winZoom[0], winZoom[1], winZoom[2], winZoom[3])
mainPlotter.setLogScale(0, False)
mainPlotter.setLogScale(1, True)
mainPlotter.ticFont = ticFont
mainPlotter.showStatBox = False
mainPlotter.showKey(False)
mainPlotter.nameX = ""
mainPlotter.nameY = ""


""" Plots all the JHep objects"""
mainPlotter.cd(1,1)
mainPlotter.draw(avEvt)
mainPlotter.draw(fit)
for i in range (len(statLine)):
	mainPlotter.draw(statBox[i])
if preliminary:
	mainPlotter.draw(prelim)	
mainPlotter.cd(2,1)
mainPlotter.draw(avEvt)
mainPlotter.draw(fitZoom)

mainPlotter.cd(1,1)
theAxes_11 = mainPlotter.getPad()
theAxes_11.setLabelSpace(0, 0.0)
theAxes_11.setLabelSpace(1, -0.01)
#theAxes_11.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, theAxes_11)
HPlotJaUtil.setTickLabelZeroPositive(theAxes_11)

mainPlotter.cd(2,1)
theAxes_21 = mainPlotter.getPad()
theAxes_21.setLabelSpace(0, 0.0)
theAxes_21.setLabelSpace(1, -0.01)
#theAxes_21.setLabelSpace(1, 0.0)
HPlotJaUtil.setTickLabelOneToPower(1, theAxes_21)
HPlotJaUtil.setTickLabelZeroPositive(theAxes_21)


""" Modifies the JaAxes and the axes labels"""
labX = mainPlotter.getLabelX()[0][0]
labX.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(0, labX, mainPlotter, 0.025)
labY = mainPlotter.getLabelY()[0][0]
labY.setFont(axisLabelFont)
HPlotJaUtil.setLabelLocationAtCenter(1, labY, mainPlotter, -0.01)
 



mainPlotter.update()

""" Saves or not the plot"""
if writeFigures:
	for i in range(len(figType)):
		outFileName = outputFile + figType[i]
		mainPlotter.export(outPath + File.separator + outFileName)
		print("Writting File : " + outPath + File.separator + outFileName)
		
print("That's all folks !")
if (not showFigures):
	exit()
